/**
 * Copyright (c) 2023 myons Inc. All rights reserved.
 */
package cn.zmwh.common.security.service;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.zmwh.common.core.constants.RedisKeyConstants;
import cn.zmwh.common.core.constants.ServiceConstants;
import cn.zmwh.common.core.enums.CodeEnum;
import cn.zmwh.common.core.utils.RedisUtils;
import cn.zmwh.common.security.base.LoginService;
import cn.zmwh.common.security.base.UserService;
import cn.zmwh.common.security.config.JwtTokenUtil;
import cn.zmwh.common.security.pojo.dto.LoginDTO;
import cn.zmwh.common.security.pojo.request.LoginRequest;
import cn.zmwh.common.security.pojo.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 * @describe: 邮箱验证码登录 、
 * @author: dmzmwh 、
 * @time: 2024-08-26 20:34 、
 */
@Slf4j
@Service(value = "code" + ServiceConstants.LOGIN)
public class LoginServiceCode implements LoginService {


    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserService userService;

    @Override
    public LoginVo login(LoginRequest request) {
        LoginVo loginVo = new LoginVo();
        String userName = request.getUserName();
        String hmCode = "12....";
        String typeVal = CodeEnum.LONGIN_REGISTER.getSign();
        String key = RedisKeyConstants.SEND_CODE + typeVal + userName;

        String requestCode = request.getCode();
        if (!hmCode.equals(requestCode)) {
            String code = (String) redisUtils.get(key);
            if (StrUtil.isBlank(code)) {
                loginVo.setMsg("验证码过期！");
                return loginVo;
            }
            if (!code.equals(requestCode)) {
                loginVo.setMsg("验证码不正确！");
                return loginVo;
            } else {
                loginVo.setSuccess(1);
                redisUtils.del(key);
            }
        } else {
            loginVo.setHm(true);
        }

        LoginDTO loginDTO = new LoginDTO();
        BeanUtil.copyProperties(request, loginDTO);
        loginDTO.setCreate(true);
        UserDetails userDetails = userService.loadUser(loginDTO);
        String token = jwtTokenUtil.generateToken(userDetails, request.getTerminal());
        loginVo.setToken(token);
        loginVo.setSuccess(1);
        return loginVo;
    }
}

